package com.lanbu.web.controller.monitor;

import com.lanbu.common.core.domain.AjaxResult;

import com.lanbu.web.controller.task.PingTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.event.ActionEvent;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

@RestController
@RequestMapping("/hikvision/live")
public class HikvisionController {

    @Value("${hikvision.timeout}")
    private int timeout;

    @Autowired
    private PingTask pingTask;

    @GetMapping()
    public AjaxResult getInfo(@RequestParam String ip,@RequestParam String port) throws Exception {
        Socket socket = null;
        try {
            // 创建 Socket 对象
            socket = new Socket();
            // 创建 SocketAddress 对象，指定目标 IP 地址和端口
            SocketAddress socketAddress = new InetSocketAddress(ip, Integer.parseInt(port));
            // 尝试连接到目标地址和端口，设置超时时间
            socket.connect(socketAddress, timeout);

            System.out.println(ip + ":" + port + " is reachable.");
            return AjaxResult.success();
        } catch (java.net.SocketTimeoutException e) {
            System.out.println(ip + ":" + port + " connection timed out.");
            return AjaxResult.error("摄像头离线"); // 连接超时，端口可能未开启或无法访问
        } catch (java.net.ConnectException e) {
            System.out.println(ip + ":" + port + " connection refused.");
            return AjaxResult.error("摄像头在线，端口错误"); // 连接被拒绝，端口可能未开启
        } catch (Exception e) {
            System.out.println("Error checking " + ip + ":" + port + ": " + e.getMessage());
            return null; // 其他异常
        } finally {
            if (socket != null) {
                try {
                    socket.close(); // 关闭 Socket 连接，释放资源
                } catch (java.io.IOException e) {
                    System.out.println("Error closing socket: " + e.getMessage());
                }
            }
        }


    }

    @GetMapping("/list")
    public AjaxResult getlist() throws Exception {
        pingTask.ryNoParams();
        return AjaxResult.success();
    }

}
